package com.gopay.scheduler.job;

import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.entrustpay.EntrustPayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务 查询主订单的状态为 30101 银行主订单状态 99 的订单 置为 失败
 * Created by lx  on 2017/6/23.
 * 委托代收00666 /网关支付 00100 12小时内 明确失败（银行主订单 91/99 ）订单状态修改为 20001
 * modify by lx 2017-6-29
 */
public class EntrustPayModifyOrderStatusJob extends GopayBaseJob {

    Logger logger = LoggerFactory.getLogger(EntrustPayModifyOrderStatusJob.class);

    @Resource(name = "entrustPayService")
    private EntrustPayService entrustPayService;

    @Resource(name = "cpsGeneralMainOrderOperClient")
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    @Resource(name = "cpsGeneralMainOrderDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;



    @Override
    protected void doJobInternal() {
        List<CpsGenMainOrder> list = entrustPayService.getEntrustPayFailedOrderList();
        logger.info("委托代收(00666)、网关支付 快捷api（00100）失败的订单数量 ：{}", list.size());

        for (CpsGenMainOrder order : list) {
            String orderId = order.getGopayOrderId();
            CpsGenMainOrder mainOrder = cpsGeneralMainOrderDAO.findByGopayOrderId(orderId);
            if (mainOrder.getTxnStaCd() == 30101 || mainOrder.getTxnStaCd() == 90101) {
                try {
                    Map<MainOrderField, String> map = new HashMap<>();
                    Date date = new Date();
                    map.put(MainOrderField.TXN_STA_CD, "20001");
                    map.put(MainOrderField.TRAN_FINISH_TIME, DateUtils.format(date));
                    map.put(MainOrderField.LAST_UPDATE_TIME, DateUtils.format(date));
                    /** modify by sh.jiao 20171227 这里不需要修改错误信息 start **/
                    /*if (StringUtils.isBlank(mainOrder.getErrMsg())){
                        map.put(MainOrderField.ERR_MSG, "订单失败，银行主订单状态:99/91");
                    }*/
                    /** modify by sh.jiao 20171227 这里不需要修改错误信息 end **/
                    if (StringUtils.isBlank(mainOrder.getErrCode())){
                        map.put(MainOrderField.ERR_CODE, "100E5042");
                    }
                    cpsGeneralMainOrderOperClient.updateMany(mainOrder.getGopayOrderId(), map);
                } catch (GopayException e) {
                    logger.error("委托代收（00666）、网关支付  快捷api（00100）更新失败订单状态异常：" + orderId);
                }
            }
        }
    }
}
